
import java.net.*;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.logging.FileHandler;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;

class UDPSC extends Thread {

    private ThreadReply mythread;
    DatagramSocket receivesocket, sendsocket;
    static Logger logger;
    static FileHandler fileHandler;
    public static boolean allowLog;
    int port;
    int sendport = 2030;

    public UDPSC(int port) {
        this.port = port;
    }

    @Override
    public void run() {
        try {

            DatagramPacket packet;
            byte[] data = new byte[1024];

            try {
                receivesocket = new DatagramSocket(port);
                sendsocket = new DatagramSocket(sendport);
            } catch (SocketException ex) {
                System.out.println(ex.toString());
            }
            while (true) {

                packet = new DatagramPacket(data, data.length);
                // nhan goi du lieu goi tu may client;
                System.out.println("Khoi dong nhan respond");
                receivesocket.receive(packet);
                // String st = new String(packet.getData(),0,packet.getLength());
                byte[] utf8bytes = Arrays.copyOf(packet.getData(), packet.getLength());
                String st = new String(utf8bytes, "UTF8");
                if (allowLog) {
                    if (logger == null) {
                        this.initLogger();
                    }
                    logger.log(Level.INFO, "{0}  {1}  {2}", new Object[]{packet.getAddress().toString(), packet.getPort(), st});
                } else {
                    UDPSC.removeLogger();
                }


                mythread = new ThreadReply(packet, sendsocket);
                mythread.start();
            }

        } catch (Exception ex) {
        }

    }

    public void stops() {
        receivesocket.close();
        sendsocket.close();
    }

    public void initLogger() {
        try {
            logger = Logger.getLogger("Receive");
            //logger.
            fileHandler = new FileHandler("app.log", true);
            fileHandler.setFormatter(new MyFormatter());
            logger.addHandler(fileHandler);
        } catch (Exception ex) {
            System.out.println(ex.toString());
        }
    }

    public static void removeLogger() {
        if (logger != null) {
            if (fileHandler != null) {
                logger.removeHandler(fileHandler);
                fileHandler.close();
            }
        }
        logger = null;


    }

    class MyFormatter extends Formatter {
        // This method is called for every log records

        public String format(LogRecord rec) {
            StringBuilder buf = new StringBuilder(1000);
            // Bold any levels >= WARNING
            buf.append(rec.getLevel());
            buf.append(' ');
            buf.append(calcDate(rec.getMillis()));
            buf.append(' ');
            buf.append(formatMessage(rec));
            buf.append('\n');
            return buf.toString();
        }

        private String calcDate(long millisecs) {
            SimpleDateFormat date_format = new SimpleDateFormat("MMM dd,yyyy HH:mm");
            Date resultdate = new Date(millisecs);
            return date_format.format(resultdate);
        }

        // This method is called just after the handler using this
        // formatter is created
        @Override
        public String getHead(Handler h) {
            return "";
        }

        // This method is called just after the handler using this
        // formatter is closed
        public String getTail(Handler h) {
            return "";
        }
    }
}
